package zfbh5

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"log"
	"os"
	"path"
	"strings"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/cashlog"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/authorized"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/utils"
)

//手动提现
func HandleQRCodeWithdrawal(c *gin.Context) {
	withdrawalModel := &request.QRCodeWithdrawalReq{}
	dingo.ErrorIf(c.Bind(withdrawalModel)).Unwrap()

	userId, err := helper.GetUserIdFromCtx(c)
	isPlace, _ := helper.GetIsPlaceFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, false)(Unauthorized)
		return
	}
	//userId := 2
	//校验参数
	if withdrawalModel.TransferType == 0 || withdrawalModel.Money == 0 {
		Response(c)("请求参数错误", CodeInvalidParam, false)(BadRequest)
		return
	}

	//校验提现金额
	// 计算已提现金额(处理成功的)
	cashTotal := dao.NewOrderDao().GetCashLogByUserId(userId).Unwrap().(int64)
	log.Println("打印测试数据--已提现金额", cashTotal)

	// 计算分红总金额
	dividTotal := dao.NewOrderDao().GetDividendsMoneyByUserId(userId).Unwrap().(int64)
	log.Println("打印测试数据--分红总金额", dividTotal)

	// 总分红 - 已提现 = 可提现金额
	cashMoney := decimal.NewFromInt(dividTotal).Sub(decimal.NewFromInt(cashTotal)).IntPart()
	log.Println("打印测试数据--可提现金额", cashMoney)

	if withdrawalModel.Money > cashMoney {
		Response(c)("提现金额不能大于可提现金额", CodeInvalidParam, false)(BadRequest)
		return
	}

	//判断是否存在未处理的订单
	cashLogInfo := dao.NewOrderDao().GetCashLogByInfo(userId).Unwrap().(cashlog.CashLogModel)
	if cashLogInfo.ID > 0 {
		Response(c)("存在有未处理订单", CodeSuccess, false)(BadRequest)
		return
	}

	// 每日限额
	list := dao.NewOrderDao().GetCashLogToMaxMoney(userId, isPlace).Unwrap().([]int64)
	if len(list) == 2 && (list[0]+withdrawalModel.Money) > list[1]*100 {
		Response(c)("每日限额", CodeSuccess, list[1])(BadRequest)
		return
	}

	userData := dao.NewUserDao().GetUserInfoById(userId)
	if userData.Err != nil {
		Response(c)("", CodeInternalServerError, false)(BadRequest)
		return
	}
	userInfo := userData.Unwrap().(*users.UserModel)

	//入库
	cashLogModel := cashlog.CashLogModel{}
	//业务参数
	cashLogModel.UserID = userId
	cashLogModel.Appid = withdrawalModel.AppId
	cashLogModel.Money = withdrawalModel.Money
	//cashLogModel.MoneyStr = strconv.Itoa(int(withdrawalModel.Money) / 100)
	cashLogModel.MoneyStr = decimal.NewFromInt(withdrawalModel.Money).Div(decimal.NewFromInt(100)).StringFixed(2)
	cashLogModel.TransferMoney = withdrawalModel.Money
	//cashLogModel.TransferMoneyStr = strconv.Itoa(int(withdrawalModel.Money) / 100)
	cashLogModel.TransferMoneyStr = decimal.NewFromInt(withdrawalModel.Money).Div(decimal.NewFromInt(100)).StringFixed(2)
	cashLogModel.TransferType = withdrawalModel.TransferType
	cashLogModel.OperateNote = withdrawalModel.OperateNote
	cashLogModel.ServiceCharge = userInfo.TaxRate

	cashLogModel.CreateAt = dingo.Time(time.Now().Unix())
	cashLogModel.TradeNo = authorized.GetRandomString(32)
	cashLogModel.State = 1
	cashLogModel.VerifyStatus = 1

	insertState := dao.NewCashDao().InsertTxCashLog(&cashLogModel).Unwrap().(bool)
	if !insertState {
		Response(c)("提现请求提交失败", CodeError, false)(Error)
		return
	}
	Response(c)("提现请求提交成功", CodeInsertSuccess, true)(OK)
	return
}

func HandleGetWithdrawalRecord(c *gin.Context) {

	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, false)(Unauthorized)
		return
	}
	//判断是否存在未处理的订单
	cashLogInfo := dao.NewOrderDao().GetCashLogByInfo(userId).Unwrap().(cashlog.CashLogModel)
	Response(c)("", CodeSuccess, cashLogInfo)(OK)
}

//上传二维码
func HandleQRCodePathUpload(c *gin.Context) {
	file, err := c.FormFile("file")

	if err != nil {
		Response(c)("上传失败!请上传文件", CodeError, nil)(Error)
		return
	}

	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, false)(Unauthorized)
		return
	}

	imgType := []string{"image/bmp", "image/png", "image/gif", "image/jpg", "image/jpeg", "image/pjpeg", "image/x-png"}
	fileExt := strings.ToLower(path.Ext(file.Filename))
	// 判断 文件类型
	if !utils.Contains(imgType, file.Header.Get("Content-Type")) {
		Response(c)("上传失败!文件类型错误", CodeError, nil)(Error)
	}
	// 判断 文件后缀
	if fileExt != ".png" && fileExt != ".jpg" && fileExt != ".gif" && fileExt != ".jpeg" {
		Response(c)("上传失败!只允许png,jpg,gif,jpeg文件", CodeError, nil)(Error)
	}

	// 判断 文件大小 1024*1024*10
	if file.Size > 10485760 {
		Response(c)("上传失败!只允许小于10M的文件", CodeError, nil)(Error)
		return
	}
	fileName := utils.Str2Md5(fmt.Sprintf("%s%s", file.Filename, time.Now().String()))

	//拼接后缀
	fileName += fileExt

	log.Println("开始上传二维码，当前用户", userId, fileName)

	fileDir := fmt.Sprintf("%s/", global.Cfg.Upload.UploadPath)
	filePath := fmt.Sprintf("%s%s", fileDir, fileName)

	// 判断文件路径是否存在
	ok, err := utils.PathExists(fileDir)
	dingo.ErrorIf(err).Unwrap()
	if !ok {
		dingo.ErrorIf(os.MkdirAll(fileDir, os.ModePerm)).Unwrap()
	}

	// 保存文件
	dingo.ErrorIf(c.SaveUploadedFile(file, filePath)).Unwrap()
	//param := &paysetting.PaySetting{}
	//入库
	//updateVal := map[string]interface{}{
	//	"wx_income_qrcode": global.Cfg.Upload.UploadReqPath + fileName,
	//}
	log.Println("上传二维码图片，", global.Cfg.Upload.UploadReqPath+fileName, "当前用户", userId)
	userModel := &users.UserModel{}
	userModel.WxIncomeQrcode = global.Cfg.Upload.UploadReqPath + fileName
	dao.NewUserDao().UpdateUserQRCode(userId, userModel).Unwrap()

	//响应给前端
	Response(c)("", CodeSuccess, utils.Join(global.Cfg.Upload.UploadReqPath, fileName))(OK)

}
